package com.symone.webcms.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.symone.webcms.mapper.MenuActionMapper;
import com.symone.webcms.mapper.MenuMapper;
import com.symone.webcms.mapper.RoleMapper;
import com.symone.webcms.model.Menu;
import com.symone.webcms.model.MenuAction;
import com.symone.webcms.model.Permission;
import com.symone.webcms.model.Role;
import com.symone.webcms.model.vo.PermissionVO;
import com.symone.webcms.model.vo.RoleFormVO;
import com.symone.webcms.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 系统用户组 服务实现类
 * </p>
 *
 * @author ArcherChu
 * @since 2018-10-30
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public List<PermissionVO> fetchAllPermissions() {
        return baseMapper.fetchAllPermissions();
    }

    @Override
    public Set<PermissionVO> fetchPermissionsById(Long id) {
        return baseMapper.fetchPermissionsById(id);
    }

    @Override
    @Transactional
    public boolean saveFormData(RoleFormVO form) {
        Role role = new Role();
        role.setId(form.getId());
        role.setCode(form.getCode());
        role.setName(form.getName());
        role.setDescription(form.getDescription());
        insertOrUpdate(role);

        //清除角色权限
        clearPermission(form.getId());

        //添加角色权限
        String[] permissions = form.getPermissions();
        List<PermissionVO> allPermissions = baseMapper.fetchAllPermissions();
        for(PermissionVO vo : allPermissions){
            for(int i = 0 ; i < permissions.length ; i ++){
                if(vo.getCode().equals(permissions[i])){
                    String url = (vo.getUrl() == null) ? "" : vo.getUrl();
                    baseMapper.insertPermission(form.getId(),vo.getCode(),url);
                }
            }
        }
        return true;
    }

    @Override
    public void clearPermission(Long id) {
        baseMapper.clearPermissionByRoleId(id);
    }
}
